<template>
  <div class="file-manager-wrapper">
    <!-- 图片模式 -->
    <div v-if="fileType === 'image'" class="image-manager">
      <div v-if="modelValue" class="image-preview">
        <img :src="getImageUrl(modelValue)" :alt="alt" />
        <div class="image-overlay">
          <el-icon class="overlay-icon" @click="previewImage">
            <ZoomIn />
          </el-icon>
          <el-icon class="overlay-icon" @click="removeImage">
            <Delete />
          </el-icon>
        </div>
      </div>
      
      <div v-else class="upload-area">
        <div class="upload-placeholder">
          <el-icon class="upload-icon">
            <Picture />
          </el-icon>
          <div class="upload-text">{{ placeholder || '选择或上传图片' }}</div>
          <div class="upload-actions">
            <FileUpload
              :model-value="modelValue"
              :file-type="fileType"
              :accept="accept"
              :max-size="maxSize"
              :disabled="disabled"
              button-text="上传图片"
              @update:model-value="handleChange"
              @change="handleChange"
            />
            <FileSelector
              :model-value="modelValue"
              :file-type="fileType"
              :disabled="disabled"
              button-text="选择图片"
              @update:model-value="handleChange"
              @change="handleChange"
            />
          </div>
          <div class="upload-tip" v-if="tip">{{ tip }}</div>
        </div>
      </div>
    </div>

    <!-- 文件模式 -->
    <div v-else class="file-manager">
      <div class="file-actions">
        <FileUpload
          :model-value="modelValue"
          :file-type="fileType"
          :accept="accept"
          :max-size="maxSize"
          :disabled="disabled"
          :multiple="multiple"
          :limit="limit"
          :button-text="uploadButtonText"
          :tip="tip"
          @update:model-value="handleChange"
          @change="handleChange"
        />

        <FileSelector
          :model-value="modelValue"
          :file-type="fileType"
          :disabled="disabled"
          :button-text="selectButtonText"
          @update:model-value="handleChange"
          @change="handleChange"
        />
      </div>

      <!-- 已选择的文件列表 -->
      <div v-if="fileList.length > 0" class="selected-files">
        <div class="file-list-header">
          <span>已选择的文件 ({{ fileList.length }})</span>
          <el-button size="small" type="danger" @click="clearFiles">
            清空全部
          </el-button>
        </div>
        
        <div class="file-list">
          <div
            v-for="(file, index) in fileList"
            :key="index"
            class="file-item"
          >
            <el-icon class="file-icon">
              <Document />
            </el-icon>
            <span class="file-name">{{ getFileName(file) }}</span>
            <el-button
              size="small"
              type="danger"
              @click="removeFile(index)"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="图片预览" width="60%" center>
      <img :src="getImageUrl(modelValue)" style="width: 100%; height: auto;" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture, ZoomIn, Delete, Document } from '@element-plus/icons-vue'
import FileUpload from '../FileUpload/index.vue'
import FileSelector from '../FileSelector/index.vue'

// 组件名称
defineOptions({
  name: 'FileManager'
})

// Props
interface Props {
  modelValue?: string | string[]
  fileType?: 'image' | 'file'
  accept?: string
  maxSize?: number
  placeholder?: string
  tip?: string
  uploadButtonText?: string
  selectButtonText?: string
  alt?: string
  disabled?: boolean
  multiple?: boolean
  limit?: number
}

const props = withDefaults(defineProps<Props>(), {
  fileType: 'image',
  accept: 'image/*',
  maxSize: 20, // 增加到20MB
  uploadButtonText: '上传文件',
  selectButtonText: '选择文件',
  disabled: false,
  multiple: false,
  limit: 1
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: string | string[]]
  'change': [value: string | string[]]
}>()

// 响应式数据
const previewVisible = ref(false)

// 计算属性
const fileList = computed(() => {
  if (props.fileType === 'file' && props.modelValue) {
    return Array.isArray(props.modelValue) ? props.modelValue : [props.modelValue]
  }
  return []
})

// 获取完整图片URL
const getImageUrl = (url: string) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  return `${import.meta.env.VITE_API_BASE_URL}${url}`
}

// 获取文件名
const getFileName = (url: string) => {
  if (!url) return ''
  return url.split('/').pop() || ''
}

// 处理值变化
const handleChange = (value: string | string[]) => {
  emit('update:modelValue', value)
  emit('change', value)
}

// 预览图片
const previewImage = () => {
  previewVisible.value = true
}

// 移除图片
const removeImage = () => {
  ElMessageBox.confirm('确定要删除这张图片吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    emit('update:modelValue', '')
    emit('change', '')
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 移除单个文件
const removeFile = (index: number) => {
  if (Array.isArray(props.modelValue)) {
    const newValue = props.modelValue.filter((_, i) => i !== index)
    emit('update:modelValue', newValue)
    emit('change', newValue)
  }
}

// 清空所有文件
const clearFiles = () => {
  ElMessageBox.confirm('确定要清空所有文件吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    emit('update:modelValue', props.multiple ? [] : '')
    emit('change', props.multiple ? [] : '')
    ElMessage.success('清空成功')
  }).catch(() => {})
}
</script>

<style scoped lang="scss">
.file-manager-wrapper {
  .image-manager {
    .image-preview {
      position: relative;
      width: 200px;
      height: 200px;
      border-radius: 8px;
      overflow: hidden;
      border: 1px solid #dcdfe6;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .image-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 16px;
        opacity: 0;
        transition: opacity 0.3s;

        &:hover {
          opacity: 1;
        }

        .overlay-icon {
          color: white;
          font-size: 24px;
          cursor: pointer;
          padding: 8px;
          border-radius: 4px;
          transition: background-color 0.3s;

          &:hover {
            background: rgba(255, 255, 255, 0.2);
          }
        }
      }
    }

    .upload-area {
      .upload-placeholder {
        width: 200px;
        height: 200px;
        border: 2px dashed #dcdfe6;
        border-radius: 8px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #8c939d;
        transition: border-color 0.3s;

        &:hover {
          border-color: #409eff;
        }

        .upload-icon {
          font-size: 48px;
          margin-bottom: 16px;
          color: #c0c4cc;
        }

        .upload-text {
          font-size: 14px;
          margin-bottom: 16px;
        }

        .upload-actions {
          display: flex;
          gap: 8px;
          margin-bottom: 8px;
        }

        .upload-tip {
          font-size: 12px;
          color: #c0c4cc;
          text-align: center;
        }
      }
    }
  }

  .file-manager {
    .file-actions {
      display: flex;
      gap: 12px;
      margin-bottom: 16px;
    }

    .selected-files {
      .file-list-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
        font-size: 14px;
        color: #606266;
      }

      .file-list {
        border: 1px solid #ebeef5;
        border-radius: 4px;
        overflow: hidden;

        .file-item {
          display: flex;
          align-items: center;
          padding: 8px 12px;
          border-bottom: 1px solid #ebeef5;
          transition: background-color 0.3s;

          &:last-child {
            border-bottom: none;
          }

          &:hover {
            background-color: #f5f7fa;
          }

          .file-icon {
            color: #409eff;
            margin-right: 8px;
          }

          .file-name {
            flex: 1;
            font-size: 14px;
            color: #606266;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }
    }
  }
}
</style>
